package com.xaicode.template.security.service;

import com.xaicode.template.security.entity.SysRole;
import com.xaicode.template.security.entity.SysUser;
import com.xaicode.template.security.repository.SysUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Locker
 * @date 2021/8/20 0020 10:25
 */
@Slf4j
@Service
public class CustomUserService implements UserDetailsService {

    @Resource
    private SysUserRepository sysUserRepository;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserRepository.findByUsername(username);
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("username not found");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : sysUser.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            log.info(role.getName());
        }

        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}
